package cn.chinasyq.photoquan;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageButton;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;

import cn.chinasyq.photoquan.base.FragmentTabAdapter;
import cn.chinasyq.photoquan.base.OnFragmentShowListener;
import cn.chinasyq.photoquan.photo.GamesActivity;
import cn.chinasyq.photoquan.photo.fragment.PhotoListFragment;
import cn.chinasyq.photoquan.user.activity.AlbumUploadActivity;
import cn.chinasyq.photoquan.user.activity.LoginActivity;
import cn.chinasyq.photoquan.user.fragment.UserManagementFragment;
import cn.chinasyq.photoquan.user.mode.UserMode;
import cn.chinasyq.photoquan.util.CameraHead;
import cn.chinasyq.photoquan.view.NotLoadedViewPager;
import cn.chinasyq.photoquan.view.PlusWindows;
import cn.chinasyq.photoquan.view.StillViewPager;
import cn.chinasyq.photoquan.view.ViewPagerTitleIndicator;
import cn.chinasyq.photoquan.view.ViewPagerTitleIndicator.TabInfo;
import cn.master.volley.commons.VolleyHelper;

public class IndexActivity extends FragmentActivity implements NotLoadedViewPager.OnPageChangeListener {

    protected int mCurrentTab = 0;
    protected int mLastTab = -1;
    // viewpager
    protected StillViewPager mPager;
    // 存放选项卡信息的列表
    protected ArrayList<TabInfo> mTabs = new ArrayList<>();
    // 选项卡控件
    protected ViewPagerTitleIndicator mIndicator;
    private ImageButton imageButton;

    @Override
    protected void onResume() {
        super.onResume();
        if (adapter != null && adapter.getItem(mCurrentTab) != null && adapter.getItem(mCurrentTab) instanceof OnFragmentShowListener) {
            ((OnFragmentShowListener) adapter.getItem(mCurrentTab)).onShow();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_index);
        VolleyHelper.init(this);
        initView();
        initTab();
        imageButton = (ImageButton) findViewById(R.id.ibtn_plus);
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (UserMode.isLogin(v.getContext())) {
                    initPlusWindows();
                    plusWindows.showMoreWindow(v);
                } else {
                    startActivity(new Intent(IndexActivity.this, LoginActivity.class));
                }
            }
        });
    }

    PlusWindows plusWindows;

    void initPlusWindows() {
        if (plusWindows == null) {
            plusWindows = new PlusWindows(this);
        }
        plusWindows.setOnMenuItemClickListener(new PlusWindows.OnMenuItemClickListener() {
            @Override
            public void onClick(int id) {
                switch (id) {
                    case R.id.button1:
                        CameraHead.Album(IndexActivity.this);
                        break;
                    case R.id.button2:
                        CameraHead.Photograph(IndexActivity.this);
                        break;
                    case R.id.button3:
                        startActivity(new Intent(IndexActivity.this, GamesActivity.class));
                        break;
                }
                plusWindows.dismiss();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        System.out.println("requestCode = " + requestCode);

        Uri bitmap = null;
        try {
            bitmap = CameraHead.callbackZoom(this, requestCode, resultCode, data, 0, 0);
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (bitmap!=null){
            Intent intent = new Intent(this, AlbumUploadActivity.class);
            intent.setData(bitmap);
            startActivity(intent);
        }
    }

    private void initView() {
        // 这里初始化界面
        mPager = (StillViewPager) findViewById(R.id.pager_matchfunction);
        mPager.setScanScroll(false);
        mPager.setOnPageChangeListener(this);
        mIndicator = (ViewPagerTitleIndicator) findViewById(R.id.pagerindicator);
        mLastTab = mCurrentTab;
    }

    @Override
    public void onPageScrolled(int position, float positionOffset,
                               int positionOffsetPixels) {
    }

    @Override
    public void onPageSelected(int position) {
        mIndicator.onSwitched(position);
        mCurrentTab = position;
        if (adapter.getItem(position) instanceof OnFragmentShowListener) {
            ((OnFragmentShowListener) adapter.getItem(position)).onShow();
        }
        hideSoftKeyboard();
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        if (state == ViewPager.SCROLL_STATE_IDLE) {
            mLastTab = mCurrentTab;
        }
    }

    public void select(int po) {
        mPager.setCurrentItem(po);
    }

    private void initTab() {
        mTabs.add(new TabInfo(FRAGMENT_ONE, CONTENT[0], icons[0], fragments[0]));
        mTabs.add(new TabInfo(FRAGMENT_TWO, CONTENT[1], icons[1], fragments[1]));
        mTabs.add(new TabInfo(FRAGMENT_THREE, CONTENT[2], icons[2], fragments[2]));

        mCurrentTab = FRAGMENT_ONE;
        adapter = new FragmentTabAdapter(this,
                getSupportFragmentManager(), mTabs);
        mPager.setAdapter(adapter);
        mIndicator.init(mCurrentTab, mTabs, mPager);
        findViewById(R.id.pagerindicator).setVisibility(View.VISIBLE);

    }
    private void readEXIF(String path) throws IOException
    {
        ExifInterface exif=new ExifInterface(path);
        //获取信息
        String time=exif.getAttribute(ExifInterface.TAG_DATETIME);
        String model=exif.getAttribute(ExifInterface.TAG_MODEL);
        String iso=exif.getAttribute(ExifInterface.TAG_IMAGE_WIDTH);

        //设置信息 tag可以自定义
//        exif.setAttribute(ExifInterface.TAG_EXPOSURE_TIME, 100+"");
//        exif.saveAttributes();
        String ex_time=exif.getAttribute(ExifInterface.TAG_IMAGE_LENGTH);

        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setTitle("EXIF信息");
        builder.setMessage(time+"\n"+model+"\n"+iso+"\n"+ex_time);
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }

        });
        builder.create().show();
    }
    public static final int FRAGMENT_ONE = 0;
    public static final int FRAGMENT_TWO = 1;
    public static final int FRAGMENT_THREE = 2;
    private static String[] CONTENT = {"影展", "", "我"};
    private static int[] icons = {R.drawable.icon_photo_selector, android.R.color.transparent, R.drawable.icon_me_selector};
    private static Class[] fragments = {PhotoListFragment.class, Fragment.class, UserManagementFragment.class};
    private FragmentTabAdapter adapter;

    /**
     * 关闭软键盘
     *
     * @return
     */
    public void hideSoftKeyboard() {
        // 当点击空白区域，隐藏软键盘
        if (getCurrentFocus() != null && getCurrentFocus().getWindowToken() != null) {
            InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
}
